﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO.Compression;
using System.IO;
using System.Net;

namespace Core.HTTPModules
{
    public sealed class HTTPEncoding : IHttpModule
    {
        /// <summary>
        /// Disposes of the resources (other than memory) used by the module 
        /// that implements <see cref="T:System.Web.IHttpModule"></see>.
        /// </summary>
        void IHttpModule.Dispose()
        {
            // Nothing to dispose; 
        }

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"></see> 
        /// that provides access to the methods, properties, and events common to 
        /// all application objects within an ASP.NET application.
        /// </param>
        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest +=new EventHandler(context_BeginRequest);
        }


        /// <summary>
        /// Handles the BeginRequest event of the context control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            string contentPath = app.Context.Request.Path;

            if ((contentPath.EndsWith(".css") && !contentPath.ToLower().EndsWith("csswitcher.css")) || contentPath.EndsWith(".png") || contentPath.EndsWith(".jpg") || contentPath.EndsWith(".js") || contentPath.EndsWith(".gif"))
            {
                SetCachingHeaders(app);
            }
        }

        /// <summary>
        /// Sets the caching headers and monitors the If-None-Match request header,
        /// to save bandwidth and CPU time.
        /// </summary>
        private static void SetCachingHeaders(HttpApplication app)
        {
            string etag = "\"" + app.Context.Request.FilePath.ToString().GetHashCode().ToString() + "\"";
            string incomingEtag = app.Request.Headers["If-None-Match"];

            app.Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
            app.Response.Cache.SetExpires(DateTime.Now.AddDays(30));
            app.Response.Cache.SetCacheability(HttpCacheability.Public);
            app.Response.Cache.SetLastModifiedFromFileDependencies();
            app.Response.Cache.SetETag(etag);

            if (String.Compare(incomingEtag, etag) == 0)
            {
                app.Response.StatusCode = (int)HttpStatusCode.NotModified;
                app.Response.End();
            }
        }

        /// <summary>
        /// Check if the browser is Internet Explorer 6 that have a known bug with compression
        /// </summary>
        /// <returns></returns>
        private static bool IsBrowserSupported()
        {
            // Because of bug in Internet Explorer 6
            HttpContext context = HttpContext.Current;
            return !(context.Request.UserAgent != null && context.Request.UserAgent.Contains("MSIE 6"));
        }
    }
}